package com.dure.hotmemory.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.dure.commonlib.util.AssetsUtil;
import com.dure.commonlib.util.PreferencesUtils;
import com.dure.commonlib.util.StatisticUtil;
import com.dure.commonlib.util.ToastUtils;
import com.dure.hotmemory.R;
import com.dure.hotmemory.bean.Planet;
import com.dure.hotmemory.config.Config;
import com.dure.hotmemory.listeners.ConfirmListener;
import com.socks.library.KLog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.Map;

/**
 * Created by longzhang on 7/25/16.
 */
public class ShareUtil {

    static ShareAction shareAction;

    public static ShareAction getInstance(Activity activity) {
        if (shareAction == null) {
            shareAction = new ShareAction(activity);
        }

        return shareAction;
    }

    public static void showShareLayout(final Activity activity) {
        final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[]
                {
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                        SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
                        SHARE_MEDIA.SINA
                };
        UMWeb web = new UMWeb(Config.HOST + "/hotmemory/download");
        web.setTitle(activity.getResources().getString(R.string.app_name));//标题
        web.setThumb(new UMImage(activity, R.mipmap.ic_launcher));  //缩略图
        web.setDescription("一起来提高记忆力吧,让你轻松取得好成绩。");//描述

        new ShareAction(activity).withText("一起来提高记忆力吧,让你轻松取得好成绩。")
                .withMedia(web)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        KLog.d("lesleixz", "share on Result" + share_media.toString());
                        PreferencesUtils.putBoolean(activity, "share_success", true);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        KLog.d("lesleixz", "share on error" + share_media.toString());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        KLog.d("lesleixz", "share on cancel" + share_media.toString());
                    }
                }).
                share();
    }

//    public static void showCustomShareLayout(final Activity activity) {
//        showCustomShareLayout(activity, null, null);
//    }

//    public static void showCustomShareLayout(final Activity activity, final Planet planet, final ConfirmListener confirmListener) {
//        SHARE_MEDIA[] displaylist = null;
//        if (confirmListener != null) {
//            displaylist = new SHARE_MEDIA[]{SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA};
////            displaylist = new SHARE_MEDIA[]{SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.SINA};
//        } else {
//            displaylist = new SHARE_MEDIA[]{SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN};
//        }
//
//        new ShareAction(activity).setDisplayList(displaylist)
////                .addButton("umeng_sharebutton_custom","umeng_sharebutton_custom","info_icon_1","info_icon_1")
//                .setShareboardclickCallback(new ShareBoardlistener() {
//                    @Override
//                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
//                        if (isClientInstalled(activity, share_media)) {
//                            String content = "";
//                            Bitmap bitmap = null;
//                            if (planet == null) {
//                                content = "一起来学习快速阅读吧,让你快速获取更多知识。";
//                                bitmap = BitmapFactory.decodeStream(AssetsUtil.getAssets(activity, "main.png"));
////                                bitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.fastread_icon);
//                            } else {
//                                content = "我正在训练" + planet.planet + ", 来一起提高阅读速度吧.";
//                                bitmap = BitmapFactory.decodeStream(AssetsUtil.getAssets(activity, planet.img));
//                            }
//                            new ShareAction(activity)
//                                    .withText(content)
//                                    .withTitle(activity.getResources().getString(R.string.app_name))
//                                    .withTargetUrl(Config.HOST+"/download")
////                                    .withMedia(new UMImage(activity, R.drawable.fastread_icon))
//                                    .withMedia(new UMImage(activity, bitmap))
//                                    .setPlatform(share_media)
//                                    .setCallback(new UMShareListener() {
//                                        @Override
//                                        public void onResult(SHARE_MEDIA share_media) {
//                                            KLog.d("lesleixz", "share on Result" + share_media.toString());
////                                            PreferencesUtils.putBoolean(activity, "share_success", true);
//                                            if (confirmListener != null) {
//                                                confirmListener.confirmed(null);
//                                            }
////                                            Toast.makeText(activity, share_media.toString() + "_share_success", Toast.LENGTH_LONG).show();
//                                            StatisticUtil.addEvent(activity, share_media.toString() + "_share_success");
//                                            ToastUtils.show(activity, "分享成功");
//                                        }
//
//                                        @Override
//                                        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
//
//                                            KLog.d("lesleixz", "share on error" + share_media.toString());
//                                        }
//
//                                        @Override
//                                        public void onCancel(SHARE_MEDIA share_media) {
//                                            KLog.d("lesleixz", "share on cancel" + share_media.toString());
//                                        }
//
//                                    })
//                                    .share();
//                        } else {
//                            Toast.makeText(activity, "请先安装客户端" + share_media, Toast.LENGTH_LONG).show();
//                        }
//                    }
//                }).open();
//    }

    public static void showCustomShareDialog(final Activity activity) {
        showCustomShareDialog(activity, null);
    }

    public static void showCustomShareDialog(final Activity activity, final Planet planet) {
        showCustomShareDialog(activity, planet, null);
    }

    public static void showCustomShareDialog(final Activity context, final Planet planet, final ConfirmListener confirmListener) {
        final Dialog dialog = new Dialog(context, R.style.customDialog);
        View view = LayoutInflater.from(context).inflate(R.layout.share_layout, null);
        TextView titleTV = (TextView) view.findViewById(R.id.title_tv);
        TextView closeBtn = (TextView) view.findViewById(R.id.close_btn);

        LinearLayout qqZoneLL = (LinearLayout) view.findViewById(R.id.qq_zone_ll);
        LinearLayout wxCircleLL = (LinearLayout) view.findViewById(R.id.wx_circle_ll);
        LinearLayout qqLL = (LinearLayout) view.findViewById(R.id.qq_ll);
        LinearLayout sinaLL = (LinearLayout) view.findViewById(R.id.sina_ll);
        LinearLayout wxLL = (LinearLayout) view.findViewById(R.id.wx_ll);

        if (confirmListener != null) {
            qqLL.setVisibility(View.GONE);
            wxLL.setVisibility(View.GONE);
//            sinaLL.setVisibility(View.GONE);
        }else{
            qqLL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.cancel();
                    handleShare(context, planet, SHARE_MEDIA.QQ, confirmListener);
                }
            });

            wxLL.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.cancel();
                    handleShare(context, planet, SHARE_MEDIA.WEIXIN, confirmListener);
                }
            });


        }

        sinaLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
                handleShare(context, planet, SHARE_MEDIA.SINA, confirmListener);
            }
        });

        qqZoneLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
                handleShare(context, planet, SHARE_MEDIA.QZONE, confirmListener);
            }
        });



        wxCircleLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
                handleShare(context, planet, SHARE_MEDIA.WEIXIN_CIRCLE, confirmListener);
            }
        });



        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });

        dialog.setCanceledOnTouchOutside(false);
        WindowManager windowManager = context.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int width = (int) (display.getWidth() * 2.5f / 3);

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setContentView(view, params);


        dialog.show();
    }

    private static void handleShare(final Activity activity, Planet planet, SHARE_MEDIA share_media,
                                    final ConfirmListener confirmListener) {
//        if (isClientInstalled(activity, share_media)) {
        String content = "";
        Bitmap bitmap = null;
//        if (planet == null) {
//
//        } else {
//            content = "我正在训练" + planet.planet + ", 来一起提高记忆力吧.";
//            bitmap = BitmapFactory.decodeStream(AssetsUtil.getAssets(activity, planet.img));
//        }
        content = "一起来提高记忆力吧,让你轻松取得好成绩。";
        bitmap = BitmapFactory.decodeStream(AssetsUtil.getAssets(activity, "main.png"));

        UMWeb web = new UMWeb(Config.HOST + "/hotmemory/download");
        web.setTitle(activity.getResources().getString(R.string.app_name));//标题
        web.setThumb(new UMImage(activity, bitmap));  //缩略图
        web.setDescription(content);//描述
        new ShareAction(activity)
                .withText(content)
                .withMedia(web)
                .setPlatform(share_media)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        KLog.d("lesleixz", "share on Result" + share_media.toString());
//                                            PreferencesUtils.putBoolean(activity, "share_success", true);
                        if (confirmListener != null) {
                            confirmListener.confirmed(null);
                        }
//                            Toast.makeText(activity, share_media.toString() + "_share_success", Toast.LENGTH_LONG).show();
                        StatisticUtil.addEvent(activity, share_media.toString() + "_share_success");
                        ToastUtils.show(activity, "分享成功");
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {

                        KLog.d("lesleixz", "share on error" + share_media.toString());
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        KLog.d("lesleixz", "share on cancel" + share_media.toString());
                    }

                })
                .share();
//        } else {
//            Toast.makeText(activity, "请先安装客户端" + share_media, Toast.LENGTH_LONG).show();
//        }
    }

    // 判断是否安装客户端
    public static boolean isClientInstalled(Activity activity, SHARE_MEDIA type) {
        return UMShareAPI.get(activity).isInstall(activity, type);
    }

    public static void doOauthVerify(final Activity activity, SHARE_MEDIA type, final ConfirmListener loginSuccessListener) {
        UMShareAPI.get(activity).doOauthVerify(activity, type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                KLog.d("lesleixz", "doOauthVerify onComplete user info:" + map.toString());

                getUserInfo(activity, share_media, loginSuccessListener);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                KLog.d("lesleixz", "doOauthVerify onError ");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                KLog.d("lesleixz", "doOauthVerify onCancel ");
            }
        });
    }

    public static void getUserInfo(Activity activity, SHARE_MEDIA type, final ConfirmListener confirmListener) {
        UMShareAPI.get(activity).getPlatformInfo(activity, type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

                String uid = map.get("uid");
                String name = map.get("name");
                String gender = map.get("gender");
                String iconurl = map.get("iconurl");

                if (confirmListener != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("uid", uid);
                    bundle.putString("name", name);
                    bundle.putString("gender", gender);
                    bundle.putString("iconurl", iconurl);
                    confirmListener.confirmed(bundle);
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {

            }
        });
    }

    public static void deleteOauth(final Activity activity, SHARE_MEDIA type) {
        UMShareAPI.get(activity).deleteOauth(activity, type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
//                KLog.d("lesleixz", "deleteOauth onComplete user info:" + map.toString());
                PreferencesUtils.putBoolean(activity, "login_success", false);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                KLog.d("lesleixz", "deleteOauth onError ");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                KLog.d("lesleixz", "deleteOauth onCancel ");
            }
        });
    }

    public static void goToMarket(Context context, String packageName) {
        Uri uri = Uri.parse("market://details?id=" + packageName);
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        try {
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }
}
